package util;

import dao.FileContentDao;
import dao.FileInformationDao;
import model.FileContent;
import model.FileInformation;
import view.MainView;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.util.Date;
import java.util.LinkedList;

/**
 * PackageName: util
 * ClassName: WriteThread
 * Author: tum0r
 * Time: 2020/5/27 19:02
 */
public class WriteThread implements Runnable {
    private MainView view;
    private final FileInformationDao fileInformationDao = new FileInformationDao();
    private final FileContentDao fileContentDao = new FileContentDao();
    private final FileOperator fileOperator = new FileOperator();
    private final String labelsPath;
    private final String resourceDBPath;
    private String progress;
    private Color progressColor;
    private int success = 0;
    private int fail = 0;

    public WriteThread(String labelsPath, String resourceDBPath, MainView view) {
        this.labelsPath = labelsPath;
        this.resourceDBPath = resourceDBPath;
        this.view = view;
    }

    @Override
    public synchronized void run() {
        try {
            LinkedList<String> labels = fileOperator.readLine(labelsPath);
            for (int i = 0; i < labels.size(); i++) {
                String s = labels.get(i);
                if (s == null || s.trim().length() == 0) {
                    continue;
                }
                String[] label = s.split(" = ");
                String fileName = new File(label[0]).getName();
                progressColor = null;
                progress = String.format("当前进度 %d/%d %.2f%%，正在写入 %s", i + 1, labels.size(), (double) (i + 1) / labels.size() * 100, fileName);
                view.setProgress(progressColor, progress);
                byte[][] data = fileOperator.readFileBytes(label[0]);
                if (data.length != 0) {
                    Hash hash = new Hash();
                    StringBuilder contentID = new StringBuilder();
                    StringBuilder fingerprint = new StringBuilder();
                    FileContent fileContent;
                    fileContentDao.open(resourceDBPath);
                    for (byte[] temp : data) {
                        fileContent = new FileContent();
                        fileContent.setData(temp);
                        fileContent.setFingerprint(hash.getHash(temp));
                        contentID.append(fileContentDao.add(fileContent));
                        contentID.append(" ");
                        fingerprint.append(fileContent.getFingerprint());
                        fingerprint.append(" ");
                    }
                    fileContentDao.commit();
                    fileContentDao.close();
                    File file = new File(label[0]);
                    int lastDot = file.getName().lastIndexOf(".");
                    String name = file.getName();
                    String type = "";
                    if (lastDot != -1) {
                        if (name.length() > lastDot + 1) {
                            type = name.substring(lastDot + 1);
                        }
                        name = name.substring(0, lastDot);
                    }
                    FileInformation fileInformation = new FileInformation();
                    fileInformation.setName(name);
                    fileInformation.setType(type);
                    fileInformation.setCreateTime(new Date(file.lastModified()));
                    fileInformation.setLastAccessTime(new Date(file.lastModified()));
                    fileInformation.setLabel(label.length == 2 ? label[1] : "");
                    fileInformation.convertSize(file.length());
                    fileInformation.setContentID(contentID.toString().trim());
                    fileInformation.setFingerprint(fingerprint.toString().trim());

                    fileInformationDao.open(resourceDBPath);
                    boolean state = fileInformationDao.add(fileInformation);
                    fileInformationDao.commit();
                    fileInformationDao.close();
                    progressColor = state ? null : Config.PROGRESS_LABEL_FONT_COLOR_ERROR;
                    progress = String.format("写入 %s %s", fileName, state ? "成功" : "失败");
                    view.setProgress(progressColor, progress);
                    switch (state ? 1 : 0) {
                        case 1:
                            success++;
                            fileOperator.deleteFile(label[0]);
                            break;
                        case 0:
                            fail++;
                            break;
                    }
                } else {
                    progressColor = Config.PROGRESS_LABEL_FONT_COLOR_ERROR;
                    progress = String.format("写入资源失败，文件 %s 不存在", label[0]);
                    view.setProgress(progressColor, progress);
                    fail++;
                    break;
                }
            }
            progressColor = null;
            progress = String.format("写入资源完成，写入成功 %d 个，失败 %d 个，写入成功文件已删除", success, fail);
            view.setProgress(progressColor, progress);
        } catch (IOException | SQLException | ClassNotFoundException | NoSuchAlgorithmException ioException) {
            progressColor = Config.PROGRESS_LABEL_FONT_COLOR_ERROR;
            progress = "写入资源失败";
            view.setProgress(progressColor, progress);
            ioException.printStackTrace();
        }
    }
}
